import { upperFirst } from "@/utils";

export function generateApi(config) {
    const { tableName, tableCNName } = config;
    let str = `
        import request from "@/utils/request";

        /**
         * 查询${tableCNName}分页数据
         */
        export function selectPage(params) {
            return request({
                url: "/api/${tableName}/selectPage",
                method: "get",
                params,
            });
        }

        /**
         * 新增${tableCNName}
         */
        export function add${upperFirst(tableName)}(data) {
            return request({
                url: "/api/${tableName}/insert",
                method: "post",
                data,
            });
        }

        /**
         * 删除${tableCNName}
         */
        export function delete${upperFirst(tableName)}(params) {
            return request({
                url: "/api/${tableName}/delete",
                method: "delete",
                params,
            });
        }

        /**
         * 更新${tableCNName}
         */
        export function update${upperFirst(tableName)}(data) {
            return request({
                url: "/api/${tableName}/update",
                method: "put",
                data,
            });
        }
    `;
    return str;
}

export function generate(config) {
    let str = ``;
    str += generateHtml(config);
    str += generateScript(config);
    str += generateStyle(config);
    return str;
}

function generateHtml(config) {
    const { queryFormOptions, btns, tableName } = config;
    const { showIndex, showSelection, columns } = config;
    const { tableCNName, editFormOptions } = config;
    const template = `<template>
        <div class = '${tableName}-container'>
            <!-- 查询模块 -->
            ${generateQueryPart(queryFormOptions, btns)}

            <div class="data">
                <!-- 表格 -->
                ${generateTable(showIndex, showSelection, columns)}

                <!-- 分页 -->
                ${generatePagination()}
            </div>

            <!-- 弹窗 -->
            ${generateDialog(tableCNName, editFormOptions, tableName)}
        </div>
    </template>`;
    return template;
}
// 生成查询表单
function generateQueryPart(options, btns) {
    const queryStr = `
    <div class="header">
        ${generateQueryForm(options)}
        ${generateTopBtns(btns)}
    </div>`;
    return queryStr;
}

// 生成顶部查询表单
function generateQueryForm(options) {
    if (!options || options.length == 0) return "";
    let str = `
    <div class="query">
        <el-form
            ref="queryForm"
            :inline="true"
            :model="queryForm"
        >
            ${options.map(
                (option) => `
                <el-form-item prop="${option.prop}">
                    <el-input
                        placeholder="${option.label}"
                        v-model="queryForm.${option.prop}"
                    ></el-input>
                </el-form-item>
            `
            )}
            <el-form-item>
                <el-button type="primary" @click="query"
                    >查询</el-button
                >
            </el-form-item>
        </el-form>
    </div>
    `;
    return str;
}

// 生成顶部操作按钮
function generateTopBtns(btns) {
    if (!btns || btns.length == 0) return "";
    let str = `
        <div class="operation">
            ${btns
                .map(
                    (btn) => `
                    <el-button type="${btn.type}" @click="${btn.funcName}">
                        ${btn.btnName}
                    </el-button>
            `
                )
                .join("")}
        </div>
    `;
    return str;
}

// 生成表格
function generateTable(showIndex = true, showSelection = true, columns = []) {
    let str = `
        <el-table
            ref="table"
            v-loading="loading"
            :data="list"
            border
            @row-click="handleRowClick"
            fit
            highlight-current-row
            @selection-change="handleSelectionChange"
        >
            ${
                showIndex
                    ? `<el-table-column type="selection" width="55" align="center">
                        </el-table-column>`
                    : ""
            }
            ${
                showSelection
                    ? `<el-table-column align="center" label="序号" width="95">
                            <template slot-scope="scope">
                                {{ scope.$index + 1 }}
                            </template>
                        </el-table-column>`
                    : ""
            }
            ${columns.map(
                (column) => `
                    <el-table-column label="${column.label}" prop="${
                    column.prop
                }" ${column.width ? `width="${column.width}"` : ""}>
                    </el-table-column>`
            )}
        </el-table>
    `;
    return str;
}

// 生成分页
function generatePagination() {
    return `
        <el-pagination
            :page-size="limit"
            class="pagination"
            background
            layout="prev, pager, next"
            :total="total"
            @current-change="handlePageChange"
        >
        </el-pagination>
    `;
}

// 生成弹窗
function generateDialog(name = "默认", options = [], table = "default") {
    let str = `
        <el-dialog
            :title="dialogType == 'edit' ? '编辑${name}' : '新建${name}'"
            :visible.sync = "dialogVisible"
            :close-on-click-modal = "false"
            width = "50%"
        >
            <el-form ref="form" :model="${table}" label-width="80px">
                ${options
                    .map(
                        (option) => `
                    <el-form-item label="${option.label}:" prop="${option.prop}">
                        <el-input v-model="${table}.${option.prop}"></el-input>
                    </el-form-item>
                `
                    )
                    .join("")}
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addOrSave">确 定</el-button>
            </span>
        </el-dialog>
    `;
    return str;
}

function generateScript(config) {
    const { tableName, editFormFields, queryFormFields } = config;
    let str = `
    <script>
        ${generateGlobalScript(tableName, editFormFields)}
        export default {
            data() {
                ${generateData(tableName, queryFormFields)}
            },
            methods: {
                ${generateMethods(tableName, queryFormFields)}
            },
            created() {
                this.get${upperFirst(tableName)}();
            }
        }
    </script>`;
    return str;
}

// import 语句
function generateGlobalScript(tableName = "", fields = {}) {
    let str = `
        import {
            selectPage,
            add${upperFirst(tableName)},
            delete${upperFirst(tableName)},
            update${upperFirst(tableName)} }
        from '@/api/${tableName}';
        const default${upperFirst(tableName)} = {
            ${Object.keys(fields)
                .map((field) => `${field}: "${fields[field]}"`)
                .join(",")}
        };
    `;
    return str;
}

// 生成data块
function generateData(tableName = "默认", queryFormFields = {}) {
    return `
        return {
            ${tableName}: Object.assign({}, default${upperFirst(tableName)}),
            list: [],
            dialogVisible: false,
            dialogType: "new",
            loading: false,
            start: 0,
            limit: 2,
            total: 0,
            selectData: [],
            queryForm: {
                ${Object.keys(queryFormFields).map(
                    (field) => `
                    ${field}: "${queryFormFields[field]}"
                `
                )}
            }
        }
    `;
}

// 生成methods
function generateMethods(tableName = "默认", queryFormFields = {}) {
    let str = `
        Add() {
            this.${tableName} = Object.assign({},
                default${upperFirst(tableName)});
            this.dialogType = "new";
            this.dialogVisible = true;
        },
        Refresh() {
            this.start = 0;
            this.$refs.queryForm.resetFields();
            this.get${upperFirst(tableName)}();
        },
        Edit() {
            if (this.selectData.length == 0) {
                return this.$message.error("未选择任何数据");
            }
            if (this.selectData.length !== 1) {
                return this.$message.error("只能操作一条数据");
            }
            this.dialogType = "edit";
            this.${tableName} = Object.assign({}, this.selectData[0]);
            this.dialogVisible = true;
        },
        Delete() {
            if (this.selectData.length == 0) {
                return this.$message.error("未选择任何数据");
            }
            if (this.selectData.length > 1) {
                return this.$message.error("只能选择一条数据");
            }
            this.$confirm("确定要删除这条数据吗?", "删除提醒", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(async () => {
                    await delete${upperFirst(
                        tableName
                    )}({ id: this.selectData[0].id });
                    this.Refresh();
                    this.$message({
                        type: "success",
                        message: "删除成功",
                    });
                })
                .catch((err) => {
                    console.error(err);
                });
        },
        async get${upperFirst(tableName)}() {
            this.loading = true;
            const res = await selectPage({
                start: this.start,
                limit: this.limit,
                ${Object.keys(queryFormFields).map(
                    (field) => `
                    ${field}: this.queryForm.${field}
                `
                )}

            });
            this.loading = false;
            const { total, records } = res.data;
            this.list = records;
            this.total = total;
        },
        handleRowClick(row) {
            this.$refs.table.toggleRowSelection(row);
        },
        handleSelectionChange(selection) {
            this.selectData = selection;
        },
        handlePageChange(param) {
            this.start = (param - 1) * this.limit;
            this.get${upperFirst(tableName)}();
        },
        query() {
            this.get${upperFirst(tableName)}();
        },
        async addOrSave() {
            let result;
            if (this.dialogType == "edit") {
                result = await update${upperFirst(
                    tableName
                )}(this.${tableName});
            } else {
                result = await add${upperFirst(tableName)}(this.${tableName});
            }
            const { code } = result;
            if (code == 200) {
                this.$message.success("操作成功");
                this.get${upperFirst(tableName)}();
            } else {
                this.$message.erro("操作失败");
            }
            this.dialogVisible = false;
        },
    `;
    return str;
}

function generateStyle({ tableName = "默认" }) {
    let str = `
    <style lang="scss" scoped>
        .${tableName}-container {
            padding: 15px;
            .header {
                display: flex;
                justify-content: space-between;
            }
            .pagination {
                margin-top: 20px;
            }
            .permission-tree {
                margin-bottom: 30px;
            }
        }
    </style>`;
    return str;
}
